﻿
@{
	ViewBag.Title = "数据采集";
}
@using Model
@model List<Model.UrlInfo>

@*<h2>在这里列出所有网址，每条网址前有多选框，以及一个开始采集按钮（采集进度视情况写或不写）</h2>
<h2>点击按钮，开始爬每个选中的网址</h2>
<h2>每搜集到一个数据，写进数据库(Data表)</h2>*@

<h2 class="sub-header">选择采集目标网址：</h2>
	<table class="table table-striped">
		<tr>
			<td>
				选择
			</td>
			<td>
				地区
			</td>
			<td>
				网址
			</td>
			<td>
				状态
			</td>
		</tr>

		@for (int i = 0; i < Model.Count; i++)
		{
			<tr>
				<td>
					<input class="checkbox" type="checkbox" name="@Model[i].Id.ToString()" checked="checked" />
				</td>
				<td>
					@Model[i].Region
				</td>
				<td>
					@Model[i].Url
				</td>
				<td>
					<text id="@Model[i].Id.ToString()">未开始</text>
				</td>
			</tr>
		}
	</table>
	@if (Session["user"] != null && ((User)Session["user"]).permission >= 2)
	{
		<div class="row right text-right">
			<button class="btn btn-default" id="start" onclick="switchbtn()">开始采集</button>
		</div>
	}

<script>
	var ID;
	var finished;
	var INTERVAL = 1000;
	function Complete() {
		var count = 0;
		for (var j = 0; j < ulist.length; j++) {
			if (!finished[ulist[j]])
				count++;
		}
		return count == 0;
	}
	function getSelectUrl() {
		ulist = [];
		finished = {};
		var boxes = document.getElementsByClassName("checkbox");
		for (var i = 0; i < boxes.length; i++)
		{
			if (boxes[i].checked) {
				ulist.push(boxes[i].name);
				finished[boxes[i].name] = false;
			}
		}
		return ulist;
	}
	function startMonitoring() {
		$.post("/DataCollect/Collect", { optCode: 1 }, function (data, textStatus, jqXHR) {
			for (var i = 0; i < data.length; i++) {
				var textid = "#" + data[i].id;
				if (!data[i].status) {
					var ST =parseInt($(textid).text(),10);
					if(isNaN(ST))
						ST = 0;
					$(textid).text(data[i].count);
					var options = {
						useEasing: false,
						useGrouping: false,
						separator: ',',
						decimal: '.',
						prefix: '',
						suffix: ''
					};
					var demo = new CountUp(data[i].id, ST, data[i].count, 0, 0.8, options);
					demo.start();
				}
				else {
					finished[data[i].id] = true;
					$(textid).text("采集完成，共：" + data[i].count);
					if (Complete()) {
						clearInterval(ID);
						$("#start").text("开始采集");
					}
				}
			}
		}, "json");
	}

	function switchbtn() {
		if ($("#start").text() == "开始采集") {
			$("#start").text("停止采集");
			ulist = getSelectUrl();

			$.ajax({
				url: "/DataCollect/Collect",
				type: "POST",
				dataType: "json",
				data: {optCode:0,ids:ulist}
			});

			ID=setInterval("startMonitoring()", INTERVAL);
		}
		else {
			$("#start").text("开始采集");
			$.post("/DataCollect/Collect", { optCode: 2 }, null, "json");
			clearInterval(ID);
		}
	}
</script>
